﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;

namespace CoolCode.Dynamic
{
    public static class ExpressionActivator
    {
        private static Dictionary<Type, Func<object>> dicExp = new Dictionary<Type, Func<object>>();

        private static Dictionary<ConstructorInfo, Func<object[], object>> dicExp2 =
            new Dictionary<ConstructorInfo, Func<object[], object>>();

        public static object CreateInstance(Type key)
        {
            Func<object> value = null;
            if (!dicExp.TryGetValue(key, out value)) 
            {
                value = CreateInstanceDelegate(key);
                dicExp[key] = value;
            }
            return value();
        }

        private static Func<object> CreateInstanceDelegate(Type type)
        {
            NewExpression newExp = Expression.New(type);
            Expression<Func<object>> lambdaExp = Expression.Lambda<Func<object>>(newExp, null);
            Func<object> func = lambdaExp.Compile();
            return func;
        }
 
    }

}
